import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.SortedSet;


public class UnicastRemoteSpelling implements RemoteSpelling
{
	private WordList my_wordlist;
	
	public UnicastRemoteSpelling(String args) throws IOException
	{
		this.my_wordlist = new WordList(args);		
	}

	public SortedSet<String> check(String the_word) throws RemoteException
	{
		Log.out("Received query for word: " + the_word);
		SortedSet<String> tempset = null;
		if(my_wordlist.isInList(the_word))
		{
			Log.out(the_word + " is spelled correctly");
		}
		else 
		{
			tempset = my_wordlist.getCloseWords(the_word);
			if (tempset.size()==0)
			Log.out(the_word + " is spelled incorrecly. There is no suggestions.");
			else {
				Iterator<String> suggestions = tempset.iterator();
				StringBuffer sb = new StringBuffer();
				while(suggestions.hasNext())
				{
					String temp = suggestions.next();
					sb.append(' ');
					sb.append(temp);
				}
				Log.out(the_word + " is spelled incorrecly. There is " + tempset.size() + " suggestions:" + sb.toString());			
			
				
			}
		}			
		return tempset;
	}

	public void add(String the_word) throws RemoteException
	{
		if (this.my_wordlist.add(the_word))
		{
			Log.out(the_word + " has been added to the wordlist");
		}
		else
		{
			Log.out(the_word + " is already in the list. No need to add");			
		}
		
	}

	public void remove(String the_word) throws RemoteException
	{
		if (this.my_wordlist.remove(the_word))
		{
			Log.out(the_word + " has been removed from the wordlist");
		}
		else
		{
			Log.out(the_word + " is not in the list. Cannot be removed");			
		}
		
	}
	

	

}
